package com.client.job.utils;

import java.util.Date;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.support.CronSequenceGenerator;
import com.client.job.core.model.MJob;
import com.client.job.core.model.MJobInstance;

@Slf4j
public class MJobUtils {
	
	/**
	 * 构建任务所在应用Id
	 * @param serverName
	 * @param serverPort
	 * @return
	 */
	public static String genServerFlag(String serverName,String serverPort){
		return serverName+"@"+serverPort;
	}
	
	/**
	 * 解析出应用名称
	 * @param serverFlag
	 * @return
	 */
	public static  String getServerName(String serverFlag) {
		return serverFlag.split("@")[0];
	}
	
	
	
	/**
	 * 解析出端口号
	 * @param serverFlag
	 * @return
	 */
	public static String getAppPort(String serverFlag) {
		return serverFlag.split("@")[1];
	}

	
	/**
	 * 解析分配策略
	 * @param mjob
	 */
	public static void  analysisParams(MJob mjob,MJobInstance mJobInstance) {
		if(mjob.getAppCounts() == 0) {
			return ;
		}
		//无需分配
		if(mjob.getZone() == 0) {			
			return ;
		}
		//时间分片
		if(mjob.getZone() == 1) {
			analysisTime(mjob,mJobInstance);
		}
		//hash分片
		if(mjob.getZone() == 2){
			analysisHash(mjob,mJobInstance);
		}
		
	}
		
	
	/**
	 * 时间分配
	 * @param mjob
	 */
	private static void analysisTime(MJob mjob,MJobInstance mJobInstance) {
		
		Date nowRime = new Date();		
		CronSequenceGenerator cronSequenceGenerator = new CronSequenceGenerator(mjob.getCron());
		Date d1 = cronSequenceGenerator.next(nowRime);
		Date d2= cronSequenceGenerator.next(d1);	
		Long totalSeconds = (d2.getTime() - d1.getTime()) /1000;		
		Long evSeconds = totalSeconds / mjob.getAppCounts();
		Long sySeconds = totalSeconds % mjob.getAppCounts();	
		Date beginTime = DateUtil.addTimeSeconds(d1, evSeconds*mJobInstance.getSort());
		Date endTime = null;
		if(mJobInstance.getSort() == (mjob.getAppCounts() -1 )) {
			endTime = DateUtil.addTimeSeconds(d1, evSeconds* (mJobInstance.getSort()+1)+sySeconds);
		}else {
			endTime = DateUtil.addTimeSeconds(d1, evSeconds* (mJobInstance.getSort()+1));
		}
		mjob.getParams().put("beginTime", beginTime);
		mjob.getParams().put("endTime", endTime);
		log.info("params:{}",mjob.getParams());
		
	}
	

	/**
	 * hash分片
	 * @param mjob
	 */
	private	 static void  analysisHash(MJob mjob,MJobInstance mJobInstance){
		mjob.getParams().put(mjob.getKeyName(),mJobInstance.getSort() % mjob.getAppCounts());
	}

}
